<template>
  <el-tabs type="border-card">
    <el-tab-pane label="商品基本信息">
      {{goodsForm}}
      <el-form ref="form" :model="goodsForm" label-width="120px">
        <el-form-item label="商品分类">
          <!--1. 一级分类-->
          <el-select v-model="goodsForm.goods.category1Id" placeholder="请选择一级分类">
            <el-option
                    v-for="item in category1List"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
          </el-select>
            <!--2. 二级分类-->
          <el-select v-model="goodsForm.goods.category2Id" placeholder="请选择二级分类">
            <el-option
                    v-for="item in category2List"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
          </el-select>
            <!--3. 三级分类-->
          <el-select v-model="goodsForm.goods.category3Id" placeholder="请选择三级分类">
            <el-option
                    v-for="item in category3List"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
          </el-select>
          模板ID:{{goodsForm.goods.typeTemplateId}}
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input type="text" v-model="goodsForm.goods.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="商品品牌">
          <el-select v-model="goodsForm.goods.brandId">
              <el-option v-for="brand in brandList" :key="brand.id" :label="brand.text" :value="brand.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="副标题">
          <el-input type="text" v-model="goodsForm.goods.caption"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input type="text" v-model="goodsForm.goods.price"></el-input>
        </el-form-item>
        <el-form-item label="商品介绍">
          <el-input type="textarea" v-model="goodsForm.goodsDesc.introduction"></el-input>
        </el-form-item>

        <el-form-item label="包装列表">
          <el-input type="textarea" v-model="goodsForm.goodsDesc.packageList"></el-input>
        </el-form-item>
        <el-form-item label="售后服务">
          <el-input type="textarea" v-model="goodsForm.goodsDesc.saleService"></el-input>
        </el-form-item>

      </el-form>
    </el-tab-pane>
    <el-tab-pane label="商品图片">
      <el-button type="success" plain size="small" @click="newFile">新建</el-button>

      <!--文件上传的对话框-->
      <el-dialog title="上传商品图片" :visible.sync="dialogFormVisible">
        {{imageEntity}}
        <el-form :model="imageEntity">
          <el-form-item label="颜色" :label-width="formLabelWidth">
            <el-input v-model="imageEntity.color" />
          </el-form-item>
          <el-form-item label="商品图片" :label-width="formLabelWidth">
            <el-upload
                    class="upload-demo"
                    :http-request="uploadFile"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :file-list="fileList"
                    list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <!--<div slot="footer" class="dialog-footer">-->
        <!--  <el-button @click="dialogFormVisible = false">取消</el-button>-->
        <!--  <el-button type="primary" @click="saveUploadPic">确定</el-button>-->
        <!--</div>-->
      </el-dialog>

      <!--展示用户上传后的图片列表-->
      <el-table
              :data="goodsForm.goodsDesc.itemImages"
              style="width: 100%">
        <el-table-column
                label="颜色"
                align="center"
                prop="color"/>
        <el-table-column
                label="图片"
                align="center">
          <template slot-scope="scope">
            <img :src="scope.row.url" width="100"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                    size="mini"
                    type="danger"
                    @click="goodsForm.goodsDesc.itemImages.splice(scope.$index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="扩展属性">
      <el-table
              :data="goodsForm.goodsDesc.customAttributeItems"
              style="width: 100%">
        <el-table-column
                align="center"
                width="200">
          <template slot-scope="scope">
             {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.value" type="text"/>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="规格">
      <el-table
              :data="specList"
              style="width: 100%">
        <el-table-column
                align="left"
                width="120">
          <template slot-scope="scope">
            {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column align="left">
          <template slot-scope="scope">
            <el-checkbox-group v-model="userSelectList[scope.$index]" size="mini" @change="userSelect">
              <el-checkbox :label="option.optionName"  :value="option.id" v-for="option in scope.row.options"></el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>
      </el-table>
      <!--显示sku商品列表-->
      <el-table
              :data="goodsForm.items"
              style="width: 100%">
        <el-table-column
                :label="specification.attributeName"
                v-for="specification in goodsForm.goodsDesc.specificationItems"
                :key="specification.attributeName"
                align="center">
          <template slot-scope="scope">
            {{scope.row.spec[specification.attributeName]}}
          </template>
        </el-table-column>

        <el-table-column align="center" label="价格"  >
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.price"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="库存" prop="num">
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.num"/>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-button type="primary" @click="save">保存</el-button>
    <el-button>返回列表</el-button>
  </el-tabs>
</template>
<style>
  .el-tabs{
    width: 80%;
    margin:0 auto!important;
  }
</style>
<script>
  import {findCategorysByParentId,save} from '@/api/goods'
  import {findItemCat} from '@/api/itemCat'
  import {findTemplateById} from '@/api/typeTemplate'
  import {findSpecListByTemplateId} from '@/api/specification'
  import {uploadFile} from "@/api/upload";

  export default {
    data() {
      return {
        goodsForm: {
          goods:{typeTemplateId:''},
          goodsDesc:{customAttributeItems:[],specificationItems:[],itemImages:[]},
          items:[]
        },
        category1List:[],       // 一级分类列表
        category2List:[],       // 二级分类列表
        category3List:[],       // 三级分类列表
        brandList:[],           // 模板id变化产生的品牌列表
        specList:[],            // 规格列表
        userSelectList:[],      // 用户选择的规格
        specNames:[],           // 规格名字数组
        formLabelWidth:'100px',
        imageEntity:{},
        dialogFormVisible:false,  // 对话框不显示
        fileList:[],              // 图片列表

      }
    },
    created() {
      //1. 查询出一级分类
      this.findCategorysByParentId()
    },
    watch:{
      //1. 监控一级分类值的变化,此时要根据这个一级分类值的变化查询出其子分类列表（二级分类列表）
      category1Id(newV,oldV){
        console.log("newV:",newV,",oldV:",oldV)
        if(newV){
          findCategorysByParentId(newV).then(({data})=>{
            console.log("data2:",data)
            this.category2List = data.itemCatList
          })
        }

      },
      //2. 监控二级分类的值的变化，此时根据二级分类查询出三级分类列表
      category2Id(newV,oldV){
        if(newV){
          findCategorysByParentId(newV).then(({data})=>{
            console.log("data2:",data)
            this.category3List = data.itemCatList
          })
        }

      },
      //3. 监控三级分类值的变化，此时在tb_item_cat表中根据三级分类查询出相关的模板id
      category3Id(newV,oldV){
        if(newV){
          findItemCat(newV).then(({data})=>{
            console.log("itemCat:",data)
            this.goodsForm.goods.typeTemplateId = data.itemCat.typeId
          })
        }

      },
      //4. 监控模板id值的变化，发生以下事情：
      typeTemplateId(newV,oldV){
        if(newV){
          findTemplateById(newV).then(({data})=>{
            console.log("template:",data)
            //4.1 第一件事：根据模板id，在模板表中得到品牌列表
            this.brandList = JSON.parse(data.typeTemplate.brandIds)
            //4.2 第二件事：加载自定义扩展属性
            this.goodsForm.goodsDesc.customAttributeItems =  JSON.parse(data.typeTemplate.customAttributeItems)
            //4.3 第三件事：加载规格及规格选项列表
            findSpecListByTemplateId(newV).then(({data})=>{
              //① 查询出规格及规格选项列表
              this.specList = data.specList
              console.log("data:",data)
              //② 根据规格个数确定userSelectList这个数组的子数组个数
              data.specList.forEach(spec=>{
                this.specNames.push(spec.text)      // 放规格名字到规格数组中
                this.userSelectList.push([])        // 放规格选项到规格选项数组中
              })
            })
          })
        }

      }
    },
    computed:{
      //1. 计算属性，可以简化变量的名字,一级分类的别名
      category1Id(){
        return this.goodsForm.goods.category1Id
      },
      //2. 计算属性，可以简化变量的名字，二级分类的别名
      category2Id(){
        return this.goodsForm.goods.category2Id
      },
      //3. 三级分类的别名
      category3Id(){
        return this.goodsForm.goods.category3Id
      },
      //4. 模板id的别名
      typeTemplateId(){
        return this.goodsForm.goods.typeTemplateId
      }
    },
    methods: {
      //1.0 用户选择，根据用户选择的规格选项值为 this.goodsForm.goodsDesc.specificationItems字段赋值。
      userSelect(){
        console.log("userSelectList:",this.userSelectList)
        console.log("specNames:",this.specNames)
        //① 合并规格名字及规格选项数组
        let specList = []
        for (let i = 0; i < this.specNames.length; i++) {
           // 规格名字
           let specName = this.specNames[i]
           // 规格选项数组
           let options = this.userSelectList[i]
           // 将规格及规格选项放到一个临时数组中
           specList.push({"attributeName":specName,"attributeValue":options})
        }
        //② 将临时数组specList赋值给this.goodsForm.goodsDesc.specificationItems 这个数组
        // 将specList这个数组中attributeValue这个子数组元素个数为0的筛选掉
        specList = specList.filter(f=>f.attributeValue.length > 0)
        // 将过滤之后的数据赋值给规格项字段this.goodsForm.goodsDesc.specificationItems
        this.goodsForm.goodsDesc.specificationItems = specList

        //③ 自动生成sku商品列表
        this.addSku()
      },
      addSku(){
        //1. 为sku商品列表添加一条默认值
        this.goodsForm.items = [{spec:{},num:999,price:10,status:0,isDefault: 0}];
        //2. 得到用户选择的规格及其规格选项列表
        let specItems = this.goodsForm.goodsDesc.specificationItems;
        //3. 循环为sku商品列表赋值
        specItems.forEach(spec=>{
          this.goodsForm.items = this.addColumn(this.goodsForm.items,spec.attributeName,spec.attributeValue)
        })
      },
      addColumn(items,attrName,attrValue){
        //1. 定义一个临时存放规格的数组
        let skuList = []
        items.forEach(item=>{
          attrValue.forEach(val => {
            //2. 将item进行深拷贝
            let newRow = JSON.parse(JSON.stringify(item))
            //3. 修改拷贝后的newRow数据
            newRow.spec[attrName] = val
            //4. 将此行放到skuList这个临时数组中
            skuList.push(newRow)
          })
        })
        console.log("skuList:",skuList)
        return skuList;
      },
      //1.1 文件上传
      uploadFile(v){
        //① 得到上传的数据中的文件对象
        let file = v.file
        //② 构造HTML5提供的表单对象
        let data = new FormData();
        data.append("file",file)
        //③ 进入文件 上传
        uploadFile(data).then(({data})=>{
          console.log("data:",data)
          if(data.code === 0){
            //1. 为当前上传的url属性赋值
            this.imageEntity.url = data.url
            //2. 将当前上传的对象this.imageEntity赋值给this.goodsForm.goodsDesc.itemImages这个数组中
            this.goodsForm.goodsDesc.itemImages.push(this.imageEntity)
            //3. 关闭上传对话框
            this.dialogFormVisible = false
          }
        })

      },
      //1.2 点击新建按钮
      newFile(){
        this.imageEntity = {}
        this.dialogFormVisible=true
        this.fileList = []
      },
      //1.2 文件上传后保存图片，关闭对话框
      saveUploadPic(){

      },
      //1.1 查询出一级分类
      findCategorysByParentId(){
          findCategorysByParentId(0).then(({data})=>{
            this.category1List = data.itemCatList
          })
      },
      // 保存商品
      save() {
        //1. 转换json对象为字符串
        this.goodsForm.goodsDesc.specificationItems = JSON.stringify(this.goodsForm.goodsDesc.specificationItems)
        this.goodsForm.goodsDesc.customAttributeItems = JSON.stringify(this.goodsForm.goodsDesc.customAttributeItems)
        this.goodsForm.goodsDesc.itemImages = JSON.stringify(this.goodsForm.goodsDesc.itemImages)
        this.goodsForm.items.forEach(item=>{
          item.spec = JSON.stringify(item.spec)
        })
        //2. 添加spu商品、spu商品描述信息、sku商品列表
        save(this.goodsForm).then(({data})=>{
          if(data.code == 0){
            this.goodsForm={
              goods:{typeTemplateId:''},
              goodsDesc:{customAttributeItems:[],specificationItems:[],itemImages:[]},
              items:[]
            }
            this.userSelectList = []
            this.specNames = []
          }
        })



      }
    }
  }
</script>